/*
*	Rene Harrer
*	ITM12
*	04.05.2014
*
*	Task: Write a program, which copies a file with the usage of systemcalls like open/read/write/close
*/

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char const *argv[])
{
	char buffer[2048];
	int source, destination;
	
	// check the arguments
	if(argc != 3) {
		fprintf(stderr, "Usage: ./yapc SOURCE DESTINATION\n");
		return 1;
	} 
		
	// open the source file for reading
	source = open(argv[1], O_RDONLY);

	// create the destination file and open it for writing and the right permissions
	destination = open(argv[2], O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);

	// check if the destination and source file exists
	if(destination < 0) {
		fprintf(stderr, "Cannot copy file, destination file already exists!\n");
		return errno;
	} else if(source < 0) {
		fprintf(stderr, "Source file doesn't exist!\n");
		remove(argv[2]);	// remove the destination file from the filesystem
		return errno;
	} else {
		// read every character of the source file and write it to the destination file
		while(read(source,buffer,1) == 1) {
			write(destination,buffer,1);
		}
		close(source);
		close(destination);
		printf("File successful copied!\n");
	}
	return 0;
}